package com.king.platform.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Order(1)
public class ControllerAspect {
  private static final Logger log = LoggerFactory.getLogger(ControllerAspect.class);

  @Pointcut("execution(public * com..*.controller..*.*(..)))")
  public void controllerPointcut() {
  }

  @Before("controllerPointcut()")
  public void doBefore(JoinPoint joinPoint) throws Throwable {
  }

  @AfterReturning(value = "controllerPointcut()", returning = "ret")
  public void doAfterReturning(Object ret) throws Throwable {
  }

  @Around("controllerPointcut()")
  public Object handleControllerPointCut(ProceedingJoinPoint joinPoint) throws Throwable {
    ServletRequestAttributes  requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    assert requestAttributes != null;
    HttpServletRequest request = requestAttributes.getRequest();
    final String remoteHost = request.getRemoteHost();
    log.info("日志处理开始：===================");
    log.info("访问得远端主机是:{}", remoteHost);
    Object result = joinPoint.proceed();
    log.info("日志处理结束：===================");
    return result;
  }

  @AfterThrowing("controllerPointcut()")
  public void handleException(JoinPoint joinPoint)  throws Throwable {

    log.info("方法运行异常：===================");
  }

}

